package com.leyantech.ecp.agenx.session.manager.handler;

import com.leyantech.ecp.agenx.common.handler.ActionHandler;
import com.leyantech.ecp.agenx.common.message.EnumWsFnType;
import com.leyantech.ecp.agenx.common.redis.entity.OnlineAssistantSession;
import com.leyantech.ecp.agenx.session.client.Assistant;

import com.google.inject.Inject;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-08.
 */
@Slf4j
public class AssistantConfigHandler extends ActionHandler {

  private final List<ConfigHandler> configHandlers;

  @Inject
  public AssistantConfigHandler(List<ConfigHandler> configHandlers) {
    this.configHandlers = configHandlers;
  }

  @Override
  public EnumWsFnType actionType() {
    return EnumWsFnType.AGENT_BUSINESS_CONFIG_MSG;
  }

  @Override
  public void handle(JsonObject message) {

    final JsonObject header = message.getJsonObject("header");
    final JsonObject body = message.getJsonObject("body");

    log.info("received assistant config {}", message);

    for (ConfigHandler configHandler : configHandlers) {
      final String configName = configHandler.configName();
      final JsonObject config = body.getJsonObject(configName);
      if (config != null) {
        config.put("ts", header.getLong("ts"))
            .put("sid", header.getString("sid"))
            .put("aid", header.getString("aid"));
        configHandler.handle(config);
        return;
      }
    }

  }

  public static Assistant toAssistant(OnlineAssistantSession onlineAssistant) {
    return Assistant.builder()
        .storeId(onlineAssistant.getStoreId())
        .assistantId(onlineAssistant.getAssistantId())
        .assistantName(onlineAssistant.getAssistantName())
        .clientUuid(onlineAssistant.getClientUuid())
        .clientVersion(onlineAssistant.getClientVersion())
        .functionList(onlineAssistant.getFunctions())
        .serviceMode(onlineAssistant.getServiceMode())
        .timestamp(onlineAssistant.getTimestamp())
        .action(onlineAssistant.getAction())
        .status(onlineAssistant.getStatus())
        .nodeId(onlineAssistant.getNodeId())
        .build();
  }

}
